package com.solution.admin.customer.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.solution.admin.auth.service.RoleService;
import com.solution.admin.company.entity.CompanyInvoiceEntity;
import com.solution.admin.company.service.CompanyInvoiceService;
import com.solution.admin.customer.entity.CompanyAddressExtendEntity;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.service.CompanyService;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.point.constants.PointConstants.IsYesNo;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.constants.PublicStatus;
import com.solution.common.constants.PublicStatus.SysCode;
import com.solution.common.controller.BaseController;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.string.StringUtil;

/**
 * 单位信息web控制层
 * @author solin
 * @date 2017-09-25 00:11:38
 */
@RequestMapping("/company")
@Controller
public class CompanyController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(CompanyController.class);

	@Autowired
	private CompanyService companyService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private KeyMapService keyMapService;
	@Autowired
	private CompanyInvoiceService companyInvoiceService; 
	@Autowired
	private CustomerService customerService;
	
	/**
	 * 单位列表查询页面
	 * @param customer
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年10月27日 上午9:07:22
	 */
	@RequestMapping("/toListCompanyPage")
	public String toListCompanyPage(CompanyEntity customer, HttpServletRequest request) {
		try {
			Long salesmanRoleId = null;
			// 默认不是销售员
			request.setAttribute("isSalesman", 0);
			// 销售员的角色ID
			List<KeyMapEntity> keyList = keyMapService.listKeyMap("salesmanRoleId");
			if (null != keyList && keyList.size() > 0) {
				salesmanRoleId = Long.parseLong(keyList.get(0).getKeyValue());
				if (roleService.checkUserRoleChkFlg(getUserId(), salesmanRoleId)) {
					// 是销售员
					request.setAttribute("isSalesman", 1);
				}
			}
//			Long adminRoleId = null;
//			// 默认不是管理员
//			request.setAttribute("isAdmin", 0);
//			// 业务员的角色ID
//			List<KeyMapEntity> keyList = keyMapService.listKeyMap("adminRoleId");
//			if (null != keyList && keyList.size() > 0) {
//				adminRoleId = Long.parseLong(keyList.get(0).getKeyValue());
//				if (roleService.checkUserRoleChkFlg(getUserId(), adminRoleId)) {
//					// 是管理员
//					request.setAttribute("isAdmin", 1);
//				}
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "customer/company_list";
	}
	
	/**
	 * 跳转到选择公司页面
	 * @param customer
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年10月30日 上午2:35:07
	 */
	@RequestMapping("/toSelectCompanyPage")
	public String toSelectCompanyPage(CompanyEntity customer, HttpServletRequest request) {
		return "customer/company_select";
	}
	
	/**
	 * 跳转到新增单位页面
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年10月27日 上午9:07:07
	 */
	@RequestMapping("/toAddCompany")
	public String toAddCompany(HttpServletRequest request) {
		request.setAttribute("opFlag", "add");
		Long salesmanRoleId = null;
		// 默认不是销售员
		request.setAttribute("isSalesman", 0);
		// 销售员的角色ID
		List<KeyMapEntity> keyList = keyMapService.listKeyMap("salesmanRoleId");
		if (null != keyList && keyList.size() > 0) {
			salesmanRoleId = Long.parseLong(keyList.get(0).getKeyValue());
			if (roleService.checkUserRoleChkFlg(getUserId(), salesmanRoleId)) {
				// 是销售员
				request.setAttribute("isSalesman", 1);
			}
		}
		return "customer/company_form";
	}
	
	/**
	 * 跳转编辑页面
	 * @return string 跳转页面路径
	 * @author solin
 	 * @date 2017-09-22 11:35:12
	 */
	@RequestMapping("/toUpdateCompany")
	public String toUpdateCompany(HttpServletRequest request) {
		// 编辑操作
		request.setAttribute("opFlag", "edit");
		// 有传客户id,说明 是用户单击了客户姓名或手机号连接进来，跳转到编辑页面时，默认选中第二个选项卡
		request.setAttribute("customerId", request.getParameter("customerId"));
		try {
			CompanyEntity company = null;
			if (StringUtil.isNotEmpty(request.getParameter("id"))) {
				Long companyId = Long.valueOf(request.getParameter("id"));
				company = companyService.getCompanyById(companyId);
				request.setAttribute("company", company);
			}
			Long salesmanRoleId = null;
			// 默认不是销售员
			request.setAttribute("isSalesman", 0);
			// 销售员的角色ID
			List<KeyMapEntity> keyList = keyMapService.listKeyMap("salesmanRoleId");
			if (null != keyList && keyList.size() > 0) {
				salesmanRoleId = Long.parseLong(keyList.get(0).getKeyValue());
				if (roleService.checkUserRoleChkFlg(getUserId(), salesmanRoleId)) {
					// 是销售员
					request.setAttribute("isSalesman", 1);
				}
			}
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("companyId", company.getId());
			// 查询客户列表
			List<CustomerEntity> customerList = customerService.listCustomer(param);
			request.setAttribute("customerList", customerList);
			
		} catch (Exception e) {
			handleException("跳转编辑客户信息页面错误", logger, e);
		}
		return "customer/company_form";
	}
	
	/**
	 * 分页查询单位信息列表
	 * @param company 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author solin
 	 * @date 2017-09-25 00:11:38
	 */
	@RequestMapping("/listCompanyPage")
	@ResponseBody
	public JSONGrid listCompanyPage(CompanyEntity company, HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userName", request.getParameter("userName"));
		paramMap.put("mobile", request.getParameter("mobile"));
		paramMap.put("companyName", request.getParameter("companyName"));
		paramMap.put("salesmanCode", request.getParameter("salesmanCode"));
		paramMap.put("customerLevel", request.getParameter("customerLevel"));
		paramMap.put("coperateFlag", request.getParameter("coperateFlag"));
		paramMap.put("customerProperty", request.getParameter("customerProperty"));
		paramMap.put("provinceCode", request.getParameter("provinceCode"));
		paramMap.put("cityCode", request.getParameter("cityCode"));
		paramMap.put("areaCode", request.getParameter("areaCode"));
		// 付款方式 01 -立即支付  02 -货到支付
		paramMap.put("allowedPayType", request.getParameter("allowedPayType"));
		
		// 销售时间
		String salesTime = request.getParameter("salesTime");
		if (StringUtil.isNotNull(salesTime)) {
			String[] salesTimes = salesTime.split(" - ");
			paramMap.put("startSalesTime", salesTimes[0]);
			paramMap.put("endSalesTime", DateUtils.getCurrentNextDay(salesTimes[1]));
		}
		
		// 注册时间
		String registeTime = request.getParameter("registeTime");
		if (StringUtil.isNotNull(registeTime)) {
			String[] registeTimes = registeTime.split(" - ");
			paramMap.put("startRegisteTime", registeTimes[0]);
			paramMap.put("endRegisteTime", DateUtils.getCurrentNextDay(registeTimes[1]));
		}
		// 登录时间
		String loginTime = request.getParameter("loginTime");
		if (StringUtil.isNotNull(loginTime)) {
			String[] loginTimes = loginTime.split(" - ");
			paramMap.put("startLoginTime", loginTimes[0]);
			paramMap.put("endLoginTime", DateUtils.getCurrentNextDay(loginTimes[1]));
		}
		// PC登录时间段
		String pcLoginTime = request.getParameter("pcLoginTime");
		if (StringUtil.isNotNull(pcLoginTime)) {
			String[] pcLoginTimes = pcLoginTime.split(" - ");
			paramMap.put("startPcLoginTime", pcLoginTimes[0]);
			paramMap.put("endPcLoginTime", DateUtils.getCurrentNextDay(pcLoginTimes[1]));
		}
		// 微信登录时间段
		String wxLoginTime = request.getParameter("wxLoginTime");
		if (StringUtil.isNotNull(wxLoginTime)) {
			String[] wxLoginTimes = wxLoginTime.split(" - ");
			paramMap.put("startWxLoginTime", wxLoginTimes[0]);
			paramMap.put("endWxLoginTime", DateUtils.getCurrentNextDay(wxLoginTimes[1]));
		}
		paramMap.put("isDelete", PublicStatus.IS_DELETE.NORMAL.getId());
		paramMap.put("userId", getUserId());
		paramMap.put("salesmanFlag", getUserAuthType());
		
		// 超级管理员查看所有
		List<KeyMapEntity> keyList = keyMapService.listKeyMap("adminRoleId");
		if (null != keyList && keyList.size() > 0) {
			Long adminRoleId = Long.parseLong(keyList.get(0).getKeyValue());
			if (roleService.checkUserRoleChkFlg(getUserId(), adminRoleId)) {
				// 是超级管理员
				paramMap.remove("salesmanFlag");
				paramMap.remove("userId");
			}
		}
		try {
			PageBean pageBean = companyService.listCompanyPage(pageParam, paramMap);
			List<CompanyEntity> companyList = (List)pageBean.getRecordList();
			if(companyList != null && companyList.size() > 0){
				for (CompanyEntity cmpy : companyList) {
					if(StringUtil.isNotEmpty(cmpy.getCustomerDetail())){
						List<CustomerEntity> customerList = JSONArray.parseArray("["+cmpy.getCustomerDetail()+"]", CustomerEntity.class);
						cmpy.setCustomerList(customerList);
						cmpy.setCustomerNum(customerList.size());
					}else{
						cmpy.setCustomerNum(0);
					}
				}
			}
			return new JSONGrid(companyList,pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询单位信息失败", logger, e);
		}
		return new JSONGrid();
	}

	/**
	 * 公司发票地址
	 * 
	 * @param request
	 * @param companyId
	 * @return JSONGrid
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年4月2日 下午5:49:43
	 */
	@RequestMapping("/listCompanyInvoicePage")
	@ResponseBody
	public JSONGrid listCompanyInvoicePage(HttpServletRequest request, String companyId) {
		int pageNum = Integer.parseInt(request.getParameter("page").toString());
		int numPerPage = Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("companyId", companyId);
			PageBean pageBean = companyInvoiceService.listPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(), pageBean.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
			return new JSONGrid();
		}
	}

	/**
	 * 新增或保存单位信息
	 * @param request 请求对象
	 * @param companyEntity 单位信息实体
	 * @return
	 * @author solin
 	 * @date 2017-09-25 00:11:38
	 */
	@RequestMapping("/saveOrUpdateCompany")
	@ResponseBody
	public Map<String, Object> saveCompany(HttpServletRequest request, CompanyEntity companyEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			if (StringUtil.isNotEmpty(request.getParameter("companyAddressExtendList"))) {
				List<CompanyAddressExtendEntity> companyAddressExtendInfo = JSONArray.parseArray(request.getParameter("companyAddressExtendList"), CompanyAddressExtendEntity.class);
				companyEntity.setCompanyAddressExtendInfo(companyAddressExtendInfo);
			}
			
			String id = request.getParameter("id");
			if(StringUtil.isNotEmpty(id)){
				result = companyService.updateCompany(companyEntity);
				resultMap.put("companyId", companyEntity.getId()); //公司ID主键
			}else{
				companyEntity.setCreater(this.getUserCode());
				result = (int)companyService.saveCompany(companyEntity);
				resultMap.put("companyId", result); //公司ID主键
				if (result > 1) {
					result = 1;
				}
			}
			resultMap.put("code", result);
		} catch (Exception e) {
			handleException("添加单位信息失败", logger, e);
		}
		return resultMap;
	}

	/**
	 * 更新单位开票信息
	 * 
	 * @param request
	 * @param companyInvoice
	 * @return Map<String,Object>
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年4月11日 上午10:55:49
	 */
	@RequestMapping("/saveCompanyBillingInfo")
	@ResponseBody
	public Map<String, Object> saveCompanyBillingInfo(HttpServletRequest request, CompanyInvoiceEntity companyInvoice) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			companyInvoice.setIsDelete(1);
			companyInvoice.setStatus(1);
			companyInvoice.setModifier(getUserName());
			if (null == companyInvoice.getId()) {
				companyInvoice.setIsDefault(0);
				companyInvoice.setCreater(getUserName());
				companyInvoiceService.create(companyInvoice);
				// 新增
			} else {
				// 修改
				companyInvoiceService.update(companyInvoice);
			}
			resultMap.put("code", 1);
			resultMap.put("msg", "保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("code", 0);
			resultMap.put("msg", "保存失败");
		}
		return resultMap;
	}

	/**
	 * 删除单位开票信息
	 * 
	 * @param request
	 * @param id
	 * @return Map<String,Object>
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年4月11日 上午10:55:42
	 */
	@RequestMapping("/delCompanyBillingInfo")
	@ResponseBody
	public Map<String, Object> saveCompanyBillingInfo(HttpServletRequest request, Long id) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			CompanyInvoiceEntity companyInvoice = new CompanyInvoiceEntity();
			// 标识已删除
			companyInvoice.setId(id);
			companyInvoice.setIsDelete(0);
			companyInvoice.setStatus(0);
			companyInvoice.setModifier(getUserName());
			// 修改
			companyInvoiceService.update(companyInvoice);
			resultMap.put("code", 1);
			resultMap.put("msg", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("code", 0);
			resultMap.put("msg", "删除失败");
		}
		return resultMap;
	}
	
	/**
	 * 设置默认发票信息
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年1月27日 下午4:57:12
	 */
	@RequestMapping("doSetDefault")
	@ResponseBody
	public Map<String,Object> doSetDefault(HttpServletRequest request) {
		Long invoiceId = Long.parseLong(request.getParameter("invoiceId"));
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			CompanyInvoiceEntity invoice = companyInvoiceService.getById(invoiceId);
			if (null != invoiceId && null != invoice) {
				CompanyInvoiceEntity modInvoice = new CompanyInvoiceEntity();
				modInvoice.setId(invoiceId);
				modInvoice.setIsDefault(Integer.parseInt(IsYesNo.YES));
				modInvoice.setModifier(getUserName());
				modInvoice.setCompanyId(invoice.getCompanyId());
				int result = companyInvoiceService.updateDefaultInvoice(modInvoice);
				if (result > 0) {
					resultMap.put(PublicStatus.RESULT_CODE, SysCode.SUCCESS);
					resultMap.put(PublicStatus.RESULT_MSG, "设置成功~");
				} else {
					resultMap.put(PublicStatus.RESULT_CODE, SysCode.ERROR);
					resultMap.put(PublicStatus.RESULT_MSG, "设置失败，请重试！");
				}
			} else {
				resultMap.put(PublicStatus.RESULT_CODE, SysCode.ERROR);
				resultMap.put(PublicStatus.RESULT_MSG, "设置失败，请重试！");
			}
		} catch (Exception e) {
			handleException("获取公司开票信息异常", logger, e);
			resultMap.put(PublicStatus.RESULT_CODE, SysCode.ERROR);
			resultMap.put(PublicStatus.RESULT_MSG, "设置失败，请重试！");
		}
		return resultMap;
	}
	
	/**
	 * 删除客户信息
	 * @param request
	 * @param customerEntity
	 * @return
	 * @author: solin
	 * @date: 2017年9月26日 下午7:47:43
	 */
	@RequestMapping("/removeCompany")
	@ResponseBody
	public Map<String, Object> removeCompany(HttpServletRequest request, CompanyEntity companyEntity){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			//获取单位ID 
			Long companyId = companyEntity.getId();
			result = companyService.deleteCompanyById(companyId);
			if (result > 0) {
				//删除相关联的人员信息
			}
			resultMap.put("code", result);
			resultMap.put("msg", "客户信息删除成功");
		} catch (Exception e) {
			resultMap.put("code", "0");
			resultMap.put("msg", "客户信息删除失败");
			handleException("客户信息删除失败", logger, e);
		}
		return resultMap;
	}
	
}
